package com.hk.sync.address.util.runner;

import com.alibaba.fastjson.JSONObject;
import com.hk.sync.address.bean.Node;
import com.hk.sync.address.bean.NodeList;
import com.hk.sync.address.service.USDTService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
@Validated
@Component
public class CheckApplicationRunner implements ApplicationRunner {

    @NotNull
    @Value("${interval}")
    private int interval;

    @Autowired
    private USDTService usdtService;
    @Autowired
    private ThreadSafe threadSafe;
    @Autowired
    private NodeList nodeList;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        log.info("application 检测节点地址数量程序开始");
        while (true) {
            try{
                boolean isLocked = threadSafe.getLock().tryLock(2, TimeUnit.SECONDS);
                if(isLocked){
                    checkNumber();
                }else {
                    log.error("CheckNodeWallet 尝试加锁出错");
                }
            }catch (Exception e){
                log.error("同步节点地址异常: "+e.getMessage());
            }finally {
                if (threadSafe.getLock().isHeldByCurrentThread()) {
                    threadSafe.getLock().unlock();
                }
            }
            Thread.sleep(interval * 1000);
        }
    }

    //校验节点地址数量
    private void checkNumber() {
        List<Integer> addressNumber = new ArrayList<Integer>();
        if (nodeList.getNodes().size() < 0) return;
        for (Node node : nodeList.getNodes()) {
            usdtService.setNode(node);
            int sum = usdtService.addressNumberByAccount("");
            log.info("节点信息: " + JSONObject.toJSONString(node.getUrl()) + "  节点地址数量: " + sum);
            if(sum < 1){
                return;
            }
            addressNumber.add(sum);
        }
        int max = Collections.max(addressNumber);
        for (int i = 0; i < addressNumber.size(); i++) {
            if (addressNumber.get(i) < max) {
                usdtService.setNode(nodeList.getNodes().get(i));
                usdtService.walletPassphrase(30);
                int jTotal = max - addressNumber.get(i);
                for (int j = 0; j < jTotal; j++) {
                    String address = usdtService.getNewAddress();
                    log.info(nodeList.getNodes().get(i).getUrl() + "  同步地址成功: " + address);
                }
                usdtService.walletLock();
            }
        }
    }
}
